package net.xdclass.rbac_shiro.config;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * Created whit IntelliJ IDEA
 * User:杨骏杰
 * Date:2021/2/16
 * Time:11:49
 * 会话管理器(前后端分离必须这样写)
 * DefaultSessionManager： 默认实现，常用于javase
 * ServletContainerSessionManager: web环境
 * DefaultWebSessionManager：常用于自定义实现
 */
public class CustomSessionManager extends DefaultWebSessionManager {

    private static final String AUTHORIZATION = "token";

    /**
     * 继承的时候，默认调用父类的构造函数，防止构造函数被覆盖
     */
    public CustomSessionManager(){
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response){

        //得到session中的token
            String sessionId = WebUtils.toHttp(request).getHeader(AUTHORIZATION);

        if(sessionId!=null){
            //传入sessionID
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE);

            //校验sessionId是否有效
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            //如果sessionId是有效的，则标记sessionID为true
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);

            return sessionId;
        }else {
            //如果为空再抛给父类的getSessionId()，让父类的方法去执行
            return super.getSessionId(request,response);
        }
    }
}
